package com.dexilaonian.activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dexilaonian.MainActivity;
import com.dexilaonian.R;
import com.dexilaonian.ui.BaseActivity;
import com.dexilaonian.utils.AnimationUtil;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.Okhttp;
import com.dexilaonian.utils.PreferencesUtil;
import com.dexilaonian.utils.WorksSizeCheckUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
public class LoginActivity extends BaseActivity {
    @Bind(R.id.et_phone)
    EditText etPhone;
    @Bind(R.id.et_pwd)
    EditText etPwd;
    @Bind(R.id.forget_pwd)
    TextView forgetPwd;
    @Bind(R.id.tv_new_user)
    TextView tvNewUser;
    @Bind(R.id.btn_login)
    Button btnLogin;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.quxiao)
    ImageView quxiao;
    @Bind(R.id.shangbufen)
    ImageView shangbufen;
    @Bind(R.id.xiabufen)
    ImageView xiabufen;
    private String phone;
    private String password;
    private String login_url;

    @Override
    protected void initData() {
        login_url = Constant.base_url + "/user/loginByPhone";
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initAnimation();
        WorksSizeCheckUtil.textChangeListener textChangeListener = new WorksSizeCheckUtil.textChangeListener(btnLogin);
        textChangeListener.addAllEditText(etPhone, etPwd);
        WorksSizeCheckUtil.setChangeListener(new WorksSizeCheckUtil.IEditTextChangeListener() {
            @Override
            public void textChange(boolean isHasContent) {
                if (isHasContent) {
                    btnLogin.setBackground(getResources().getDrawable(R.drawable.button));
                    btnLogin.setClickable(true);
                } else {
                    btnLogin.setBackground(getResources().getDrawable(R.drawable.graybutton));
                    btnLogin.setClickable(false);
                }
            }
        });
        //Log.e("lo", "runnable线程： " + Thread.currentThread().getId()+ " name:" + Thread.currentThread().getName());
        etPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                quxiao.setVisibility(View.VISIBLE);
            }
        });
    }

    private void initAnimation() {
        TranslateAnimation translateAnimation = AnimationUtil.moveToViewBottom();
        shangbufen.setAnimation(translateAnimation);
        TranslateAnimation translateAnimation1 = AnimationUtil.moveToViewLocation();
        xiabufen.setAnimation(translateAnimation1);
    }

    @OnClick({R.id.back, R.id.forget_pwd, R.id.tv_new_user, R.id.btn_login, R.id.quxiao})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.forget_pwd:
                startActivity(new Intent(LoginActivity.this, Phone_Find_PwdActivity.class));
                break;
            case R.id.tv_new_user:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                break;
            case R.id.quxiao:
                etPwd.setText("");
                quxiao.setVisibility(View.GONE);
                break;
            case R.id.btn_login:
                phone = etPhone.getText().toString().trim();
                password = etPwd.getText().toString().trim();

                if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(password) || phone.length() != 11) {
                    Toast.makeText(this, "手机号码或密码不正确", Toast.LENGTH_SHORT).show();
                } else {
                    if (password.length() < 6 || password.length() > 20) {
                        showToast("密码长度不正确");
                        return;
                    } else {
                        login1(phone, password);
                    }
                }
                break;
        }
    }
    //记录用户首次点击返回键的时间
    private long firstTime=0;
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode){
            case KeyEvent.KEYCODE_BACK:

                long secondTime=System.currentTimeMillis();
                if(secondTime-firstTime>2000){
                    Toast.makeText(LoginActivity.this,"再按一次退出程序",Toast.LENGTH_SHORT).show();
                    firstTime=secondTime;
                    return true;
                }else{
                    System.exit(0);
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }
    private void login1(String phone, String password) {
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("password", password);
        Okhttp.postString(false, login_url, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showProgressBar(false);
                showToast(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                try {
                    JSONObject object = new JSONObject(response);
                    int status = Integer.parseInt(object.optString("status"));
                    if (status == 9) {
                        showToast("密码长度不正确");
                        return;
                    }
                    if (status == 10) {
                        showToast("登录名无法处理（不是手机号也不是邮箱）");
                        return;
                    }
                    if (status == 11) {
                        showToast("用户未注册");
                        return;
                    }
                    if (status == 12) {
                        showToast("登录密码错误");
                        return;
                    }
                    if (status == 13) {
                        showToast("用户已冻结");
                        return;
                    }
                    if (status == 14) {
                        showToast("用户暂时冻结");
                        return;
                    }

                    if (status == 0) {
                        JSONObject data = object.optJSONObject("data");
                        if (data != null) {
                            String token = data.optString("token");
                            String appuserId = data.optString("appuserId");

                            if (!TextUtils.isEmpty(token)) {
                                PreferencesUtil.putString(LoginActivity.this, Constant.KEY, token);
                            }
                            if (!TextUtils.isEmpty(token)) {
                                PreferencesUtil.putString(LoginActivity.this, Constant.APPUSERID, appuserId);
                            }
                        }
                        showToast("登录成功");
                     /*   Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        //intent.putExtra("user", 1);
                        startActivity(intent);*/
                        finish();
                    } else {
                        showToast("登录失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
            }
        });
    }

}
